package com.devilvan.betrice.bilibili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devilvan.betrice.bilibili.dto.BilibiliMemberDto;
import com.devilvan.betrice.bilibili.po.BilibiliMemberPo;
import com.devilvan.betrice.bilibili.service.BilibiliMemberService;
import com.devilvan.betrice.bilibili.mapper.BilibiliMemberMapper;
import com.devilvan.betrice.bilibili.repository.BilibiliMemberRepository;
import com.devilvan.betrice.util.UEmpty;
import com.devilvan.betrice.util.UCopy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Evad.Wu
 * @Description Bilibili-用户信息表 业务逻辑类
 * @date 2022-12-22
 */
@Service
public class BilibiliMemberServiceImpl extends ServiceImpl<BilibiliMemberMapper, BilibiliMemberPo> implements BilibiliMemberService {
    @Resource(name = "bilibiliMemberRepository")
    private BilibiliMemberRepository bilibiliMemberRepository;

    @Override
    public BilibiliMemberPo saveUpdate(BilibiliMemberDto bilibiliMemberDto) {
        BilibiliMemberPo bilibiliMemberPo = new BilibiliMemberPo();
        UCopy.fullCopy(bilibiliMemberDto, bilibiliMemberPo);
        return bilibiliMemberRepository.saveAndFlush(bilibiliMemberPo);
    }

    @Override
    public List<BilibiliMemberPo> saveUpdateBatch(List<BilibiliMemberDto> list) {
        List<BilibiliMemberPo> bilibiliMemberPoList = UCopy.fullCopyCollections(list, BilibiliMemberPo.class);
        return bilibiliMemberRepository.saveAllAndFlush(bilibiliMemberPoList);
    }

    @Override
    public void distinctSaveMemberByMid(List<BilibiliMemberDto> bilibiliMemberDtoList) {
        if (UEmpty.isEmpty(bilibiliMemberDtoList)) {
            return;
        }
        List<BilibiliMemberPo> bilibiliMemberPoList = UCopy.fullCopyCollections(bilibiliMemberDtoList, BilibiliMemberPo.class);
        List<Long> midList = bilibiliMemberPoList.stream().map(BilibiliMemberPo::getMid).toList();
        LambdaQueryWrapper<BilibiliMemberPo> queryWrapper = new QueryWrapper<BilibiliMemberPo>().lambda();
        queryWrapper.in(BilibiliMemberPo::getMid, midList);
        queryWrapper.groupBy(BilibiliMemberPo::getMid);
        List<BilibiliMemberPo> existMemberPoList = this.list(queryWrapper);
        List<BilibiliMemberPo> distinctMemberPoList = UCopy.checkAssemble(bilibiliMemberPoList, existMemberPoList, BilibiliMemberPo::getMid);
        bilibiliMemberRepository.saveAllAndFlush(distinctMemberPoList);
    }
}
